package com.myjoje.service.system;

import com.myjoje.base.BaseService;
import com.myjoje.bean.system.DeptBean;
import com.myjoje.bean.system.MenuBean;
import com.myjoje.bean.system.RoleBean;
import com.myjoje.bean.system.UserBean;
import com.myjoje.config.AppCache;
import com.myjoje.dao.system.UserDao;
import com.myjoje.jpa.RoleJpa;
import com.myjoje.jpa.UserJpa;
import com.myjoje.util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户，角色，以及关系维护
 */
@Service
public class UserService extends BaseService {

    @Autowired
    private RoleJpa roleJpa;
    @Autowired
    private UserJpa userJpa;
    @Autowired
    private UserDao userDao;
    @Autowired
    private MenuService menuService;
    @Autowired
    private DeptService deptService;


    /**
     * 根据身份查找用户(username or phoneNum or openId)
     */
    public UserBean getUserByPrincipal(String principal) {

        return userDao.getUserByPrincipal(principal);
    }


    /**
     * 获取用户列表
     */
    public List<UserBean> getUserList(Integer currentPage, Integer pageSize, Map params) {
        List<UserBean> list = userDao.get(currentPage, pageSize, params);
        //处理密码和openId
        list = list.stream().map(user -> {
            user.setPassword(null);
            user.setOpenid(null);
            return user;
        }).collect(Collectors.toList());
        return list;
    }

    /**
     * 获取用户数量
     */
    public Long getUserCount(Map map) {
        return userDao.getCount(map);
    }


    /**
     * 角色列表
     */
    public List<RoleBean> getRoleList(Integer currentPage, Integer pageSize, Map params) {
        return userDao.getRoleList(currentPage, pageSize, params);
    }

    /**
     * 角色数量
     */
    public Long getRoleCount(Map params) {
        return userDao.getRoleCount(params);
    }

    /**
     * 添加或更新用户
     */
    public Message saveOrUpdateUser(UserBean bean) {
        String id = bean.getId();
        //验证用户名
        String username = bean.getUsername();
        if (isEmpty(username)) {
            return Message.error("用户名不能为空");
        }
        //电话号码
        String phoneNum = bean.getPhoneNum();
        //添加
        if (isEmpty(id)) {
            if (isUsernameExists(username)) {
                return Message.error("用户名已存在");
            }
            //电话号码不为空，验证电话号码
            if (isNotEmpty(phoneNum) && isPhoneNumExists(phoneNum)) {
                return Message.error("电话号码已存在");
            }
            saveUser(bean);
            return Message.success("保存成功");
        } else {
            UserBean oldBean = getUserById(id);
            if (null != oldBean) {
                //用户名不允许修改
                if (!oldBean.getUsername().equals(username)) {
                    return Message.error("用户名不允许修改");
                }
                //手机号码允许修改
                String oldPhoneNum = oldBean.getPhoneNum();
                if (isNotEmpty(phoneNum) || isNotEmpty(oldPhoneNum)) {
                    if (!oldPhoneNum.equals(phoneNum)) {
                        if (isPhoneNumExists(phoneNum)) {
                            return Message.error("电话号码已存在");
                        }
                    }
                }
                bean.setPassword(oldBean.getPassword());
                bean.setOpenid(oldBean.getOpenid());
                saveUser(bean);
                return Message.success("更新成功");
            } else {
                return Message.error("佛祖保佑，永无BUG");
            }
        }
    }

    /**
     * 根据id得到用户
     */
    public UserBean getUserById(String id) {
        if (isEmpty(id)) {
            return null;
        }
        Optional<UserBean> optional = userJpa.findById(id);
        return optional.isPresent() ? optional.get() : null;
    }

    /**
     * 添加或保存用户
     */
    private UserBean saveUser(UserBean bean) {
        if (isEmpty(bean.getId())) {
            bean.setStatus(UserBean.STATUS_NORMAL);
            bean.setPassword(getDefaultPassword());
            bean.setCreateTime(getDateTime());
            if (isEmpty(bean.getCreateUser())) {
                bean.setCreateUser(getCurrentUserId());
            }
        } else {
            bean.setModifyTime(getDateTime());
            if (isEmpty(bean.getModifyUser())) {
                bean.setModifyUser(getCurrentUserId());
            }
        }
        userJpa.save(bean);
        return bean;
    }

    /**
     * 电话号码是否存在
     */
    private boolean isPhoneNumExists(String phoneNum) {
        return userJpa.countByPhoneNumAndStatus(phoneNum, UserBean.STATUS_NORMAL) > 0;
    }

    /**
     * 用户名是否存在
     */
    private boolean isUsernameExists(String username) {
        return userJpa.countByUsernameAndStatus(username, UserBean.STATUS_NORMAL) > 0;
    }


    /**
     * 添加或更新角色
     */
    public Message saveOrUpdateRole(RoleBean bean) {
        String id = bean.getId();
        String name = bean.getName();
        if (isEmpty(name)) {
            return Message.error("角色名称不能为空");
        }
        String code = bean.getCode();
        if (isEmpty(code)) {
            return Message.error("角色编码不能为空");
        }
        if (isEmpty(id)) {//添加
            if (isRoleNameExists(name)) {
                return Message.error("角色名称已经存在");
            }
            if (isRoleCodeExists(code)) {
                return Message.error("角色编码已经存在");
            }
            saveRole(bean);
            AppCache.setRole(code, bean.getId());
            return Message.success("保存成功");
        } else {//更新
            RoleBean oldBean = getRoleById(id);
            if (null != oldBean) {
                String oldName = oldBean.getName();
                if (name.equals(oldName) && bean.getPriority().equals(oldBean.getPriority())) {
                    return Message.error("请修改后提交");
                }
                //角色名称和原来的不同
                if (!name.equals(oldName)) {
                    if (isRoleNameExists(name)) {
                        return Message.error("角色名称已经存在");
                    }
                }
                bean.setCode(oldBean.getCode());
                saveRole(bean);
                return Message.success("修改成功");
            } else {
                return Message.error("佛祖保佑，永无BUG");
            }
        }
    }

    /**
     * 根据id获取角色
     */
    private RoleBean getRoleById(String id) {
        if (isEmpty(id)) {
            return null;
        }
        Optional<RoleBean> optional = roleJpa.findById(id);
        return optional.isPresent() ? optional.get() : null;
    }

    /**
     * 添加或保存角色
     */
    private RoleBean saveRole(RoleBean bean) {
        if (isEmpty(bean.getId())) {
            bean.setCreateTime(getDateTime());
            if (isEmpty(bean.getCreateUser())) {
                bean.setCreateUser(getCurrentUserId());
            }
        } else {
            bean.setModifyTime(getDateTime());
            if (isEmpty(bean.getModifyUser())) {
                bean.setModifyUser(getCurrentUserId());
            }
        }
        roleJpa.save(bean);
        return bean;
    }

    /**
     * 角色编码是否存在
     */
    private boolean isRoleCodeExists(String code) {
        return roleJpa.countByCode(code) > 0;
    }

    /**
     * 角色名称是否存在
     */
    private boolean isRoleNameExists(String name) {
        return roleJpa.countByName(name) > 0;
    }


    /**
     * 删除用户
     */
    public Object deleteUser(String id) {
        Map map = getMap("status", UserBean.STATUS_DELETE);
        userDao.updateById(id, getCurrentUserId(), map);
        return Message.success("删除成功");
    }

    /**
     * 为超级管理添加所有的部门
     */
    public void updateRootDeptIds(String deptIds) {
        userDao.updateRootDeptIds(deptIds);
    }

    /**
     * 根据部门id获取用户数量
     */
    public Long getUserCountByDeptId(String deptId) {
        Map map = getMap("deptId", deptId);
        return userDao.getCount(map);
    }

    /**
     * 移除用户部门
     */
    public Message deleteUserDept(String userId, String removeDeptId) {
        if (isEmpty(removeDeptId)) {
            return Message.error("部门id不能为空");
        }
        Optional<UserBean> optional = userJpa.findById(userId);
        if (optional.isPresent()) {
            UserBean bean = optional.get();
            List<String> list = Arrays.asList(bean.getDeptIds().split(","));
            String deptIds = list.stream().
                    filter(deptId -> !deptId.equals(removeDeptId))
                    .collect(Collectors.joining(","));
            bean.setDeptIds(deptIds);
            bean.setModifyTime(getDateTime());
            bean.setModifyUser(getCurrentUserId());
            userJpa.save(bean);
        }
        return Message.success("移除成功");
    }

    /**
     * 移除用户角色
     */
    public Object deleteUserRole(String userId, String removeRoleId) {
        if (isEmpty(removeRoleId)) {
            return Message.error("角色id不能为空");
        }
        Optional<UserBean> optional = userJpa.findById(userId);
        if (optional.isPresent()) {
            UserBean bean = optional.get();
            List<String> list = Arrays.asList(bean.getRoleIds().split(","));
            String roleIds = list.stream().
                    filter(roleId -> !roleId.equals(removeRoleId))
                    .collect(Collectors.joining(","));
            bean.setRoleIds(roleIds);
            bean.setModifyTime(getDateTime());
            bean.setModifyUser(getCurrentUserId());
            userJpa.save(bean);
        }
        return Message.success("移除成功");
    }

    /**
     * 添加用户部门
     */
    public Message addUserDept(String userId, String deptId) {
        if (isEmpty(deptId)) {
            return Message.error("部门id不能为空");
        }
        Optional<UserBean> optional = userJpa.findById(userId);
        if (optional.isPresent()) {
            UserBean bean = optional.get();
            String deptIds = bean.getDeptIds();
            //部门id为空
            if (isEmpty(deptIds)) {
                bean.setDeptIds(deptId);
            } else {
                //deptIds不包含追加
                if (!deptIds.contains(deptId)) {
                    List<String> list = new ArrayList<>(Arrays.asList(deptIds.split(",")));

                    list.add(deptId);
                    deptIds = list.stream().collect(Collectors.joining(","));
                    bean.setDeptIds(deptIds);
                }
            }
            bean.setModifyTime(getDateTime());
            bean.setModifyUser(getCurrentUserId());
            userJpa.save(bean);
            return Message.success("添加成功");
        }
        return Message.error("用户不存在");
    }

    /**
     * 根据角色获取用户
     */
    public Message getUserByRole(String role) {
        return Message.success("请求成功", getUserListByRole(role));
    }

    public List<UserBean> getUserListByRole(String role) {
        return getUserListByRoleAndDept(role, null);
    }

    public List<UserBean> getUserListByRoleAndDept(String role, String dept) {
        Map map = getMap("deptId", dept);
        map.put("roleId", role);
        if ("2".equals(role)) {
            map.put("roleId", AppCache.getRoleAdmin());
        }
        List<UserBean> list = getUserList(null, null, map);
        return list;
    }


    /**
     * 获取用户菜单
     */
    public Object getUserMenu() {
        //用户的角色
        String roleIds = getCurrentUser().getRoleIds();
        List<MenuBean> list = new ArrayList<>();
        if (isEmpty(roleIds)) {
            return Message.success("请求成功", list);
        } else {
            list = menuService.getMenuByRoleIds(roleIds);
            return Message.success("请求成功", list);
        }

    }

    /**
     * 获取用户部门
     */
    public Object getUserDept() {
        UserBean user = getCurrentUser();
        String deptIds = user.getDeptIds();
        List<DeptBean> list = new ArrayList<>();
        if (isNotEmpty(deptIds)) {
            list = deptService.getDeptByIds(new HashSet<>(Arrays.asList(deptIds.split(","))));
        }
        return Message.success("请求成功", list);
    }
}
